package com.league.blog.system.shiro.custom;

import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.CollectionUtils;
import org.apache.shiro.web.filter.authz.AuthorizationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;
import java.util.Set;

/**
 * @author 黄豪琦
 * 日期:2019-07-03 16:30
 * 说明: 自定义role过滤器
 */
public class CustomRolesAuthorizationFilter extends AuthorizationFilter {

    public CustomRolesAuthorizationFilter() {
    }

    @Override
    public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws IOException {
        Subject subject = this.getSubject(request, response);
        //获取当前路径所需要的角色
        String[] rolesArray = (String[])((String[])mappedValue);
        //如果有配置，那说明对角色有要求
        if (rolesArray != null && rolesArray.length != 0) {
            Set<String> roles = CollectionUtils.asSet(rolesArray);
            boolean flat = false;
            for(String item : roles){
                //判断是否有这个角色
                if(subject.hasRole(item)){
                    flat = true;
                }
            }
            return flat;
        } else {
            return true;
        }
    }
}
